﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel.Security.Tokens;
using System.ServiceModel.Description;

namespace ConsoleApplication3
{
	internal class MyClientCredentialsSecurityTokenManager :
	ClientCredentialsSecurityTokenManager
	{
		MyClientCredentials credentials;

		public MyClientCredentialsSecurityTokenManager(
			MyClientCredentials credentials)
			: base(credentials)
		{
			this.credentials = credentials;
		}

		public override SecurityTokenProvider CreateSecurityTokenProvider(
			SecurityTokenRequirement requirement)
		{
			SecurityTokenProvider result = null;
			if (requirement.TokenType == SecurityTokenTypes.X509Certificate && requirement.RequireCryptographicToken)
			{

				MessageDirection direction = requirement.GetProperty
					<MessageDirection>(ServiceModelSecurityTokenRequirement.
					MessageDirectionProperty);
				switch (direction)
				{
					case MessageDirection.Output:
						if (requirement.KeyUsage == SecurityKeyUsage.Signature)
						{
							result = new X509SecurityTokenProvider(
								this.credentials.ClientSigningCertificate);
						}
						else
						{
							result = new X509SecurityTokenProvider(this.credentials.
								ServiceEncryptingCertificate);
						}
						break;
					case MessageDirection.Input:
						if (requirement.KeyUsage == SecurityKeyUsage.Signature)
						{
							result = new X509SecurityTokenProvider(this.
								credentials.ServiceSigningCertificate);
						}
						else
						{
							result = new X509SecurityTokenProvider(credentials.
								ClientEncryptingCertificate);
						}
						break;
					default:
						result = base.CreateSecurityTokenProvider(requirement);
						break;
				}
				
			}
			else
			{
				result = base.CreateSecurityTokenProvider(requirement);
			}

			return result;
		}

		public override SecurityTokenAuthenticator
			CreateSecurityTokenAuthenticator(SecurityTokenRequirement
			tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
		{
			return base.CreateSecurityTokenAuthenticator(tokenRequirement,
				out outOfBandTokenResolver);
		}
	}
}
